package com.chen.proxiedServerForTest.httpserver;

import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServer3 extends Thread {
    final int port = 8803;

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("server3启动");
            ExecutorService executorService = Executors.newFixedThreadPool(100);
            while (true){
                Socket socket = serverSocket.accept();
                executorService.execute(()->{
                    service(socket);
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void service(Socket socket) {
        PrintWriter printWriter = null;
        try {
            String body = "Hello server3";
            printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            printWriter.println("Content-Length:" + body.getBytes().length);
            printWriter.println();
            printWriter.write(body);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(printWriter);
            close(socket);
        }
    }

    void close(Closeable closeable){
        if (closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            HttpServer3 server3 = new HttpServer3();
            server3.join();
            server3.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
